package io.github.soiff.mdoc.holder;

import com.sun.tools.javac.code.Symbol;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by zhangh on 10/26/2016.
 *
 * @author : zhangh@dtdream.com
 * @version : 1.0.0
 * @since : 1.8
 */
@SuppressWarnings({"unchecked", "unused", "WeakerAccess"})
public class Classes {
    private static final Classes INSTANCE = new Classes();
    private static final Class<?> DEFAULT_CLASS = Object.class;
    private static final Object DEFAULT_VALUE = new Object();

    private ConcurrentMap<String, Symbol.ClassSymbol> symbols = new ConcurrentHashMap<>(32);
    private ConcurrentMap<String, Class<?>> classes = new ConcurrentHashMap<>(32);
    private ConcurrentMap<String, Object> defaults = new ConcurrentHashMap<>(32);

    private Classes() {
    }

    public static Classes getInstance() {
        return INSTANCE;
    }

    public Symbol.ClassSymbol getDeclare(String qualifier) {
        return symbols.get(qualifier);
    }

    public Class<?> getClass(String qualifier) {
        return classes.get(qualifier);
    }

    public<T> T getDefault(String qualifier) {
        return (T)defaults.get(qualifier);
    }

    public void add(Class<?> clazz) {
        classes.put(clazz.getCanonicalName(), clazz);
    }

    public void add(Object value) {
        classes.put(value.getClass().getCanonicalName(), value.getClass());
        defaults.put(value.getClass().getCanonicalName(), value);
    }

    public void add(Symbol.ClassSymbol symbol) {
        add(symbol, null);
    }

    public void add(Symbol.ClassSymbol symbol, Object value) {
        final String qualifier = symbol.getQualifiedName().toString();
        symbols.put(qualifier, symbol);
        classes.put(qualifier, DEFAULT_CLASS);
        defaults.put(qualifier, null == value ? DEFAULT_VALUE : value);
    }
}
